<template >
  <div>
    <a-spin :spinning="loading">
      <div class="operate-page-content schedule-route-container">
        <a-form :model="formState" ref="formRef" layout="vertical">
          <a-row :gutter="40">
            <a-col :span="5">
              <a-form-item :label="$t('other.versionName')"  name="name">
                <a-input v-model:value.trim="formState.name" :disabled="true" placeholder="" />
              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-form-item :label="$t('hangManage.startProcess')" name="firstProcess">
                <a-select :placeholder="$t('common.pleaseSelect')" allowClear v-model:value="formState.firstProcess" :disabled="disabled">
                  <a-select-option v-for="(item, index) in processOption" :key="index" :value="item.processDetailId">{{item.name}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-form-item :label="$t('hangManage.endProcess')" name="lastProcess">
                <a-select :placeholder="$t('common.pleaseSelect')" allowClear v-model:value="formState.lastProcess" :disabled="disabled">
                  <a-select-option v-for="(item, index) in processOption" :key="index" :value="item.processDetailId">{{item.name}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <div class="schedule-roadmap-container">
          <a-row>
            <a-col :span="16" class="list-container">
              <a-row class="operate-row">
                <a-col :span="10">{{$t('hangManage.roadList')}}</a-col>

                <a-col :span="14" class="text-right">
                  <a-space>
                    <a-button type="primary" @click="toggleAll(true)">{{ $t('common.expandAll') }}</a-button>
                    <a-button type="primary" @click="toggleAll(false)">{{ $t('common.packUpAll') }}</a-button>
                    <a-button type="warning" @click="clearList" v-if="!disabled">{{ $t('common.clearList') }}</a-button>
                  </a-space>
                </a-col>
              </a-row>
              <header>
                <div v-for="(item, index) in (disabled ? viewRouteHeader :routeHeader)" :key="index">{{item}}</div>
              </header>

              <draggable :list="tableList" is='draggable' :disabled="disabled" filter=".forbid" handle=".process-box" animation="300" :scroll="true" force-fallback="true" group="out" item-key="index" :allbackOnBody="true" @add="add" @sort="handleSort" @start="handleStart">
                <template #item="{element, index}">
                  <div :class="{'forbid': index== 0}">
                    <div class="relative">
                      <span class="toggle-box">
                        <minus-square-outlined v-if="element.open" @click="() => {element.open = false}" />
                        <!-- <plus-square-outlined style="color: red;background: white" fill="red" v-else @click="() =>{ element.open = true}" /> -->
                        <plus-square-outlined v-else @click="() =>{ element.open = true}" />
                      </span>
                      <div class="mt-12 process-box">
                        <div>
                          <span>{{element.sort}}</span>
                        </div>
                        <div>
                          <a-checkbox class="forbid" v-model:checked="element.effect" :disabled="disabled || index ==0">{{ $t('hangManage.effect') }}</a-checkbox>
                        </div>
                        <div>
                          <a-checkbox class="forbid" v-model:checked="element.forwardMerge" @change="onCheckChange(element)" :disabled="disabled|| index ==0">
                            {{ $t('other.forwardMerge') }}</a-checkbox>
                        </div>
                        <div>{{ element.processNo }}，{{ element.name }}</div>
                        <div></div>
                        <div v-if="!disabled" class="forbid">
                          <span class="close-icon" v-if="index!=0" @click="handelCancel(index, false)">
                            <close-outlined />
                          </span>
                        </div>
                      </div>
                    </div>
                    <draggable v-model="element.moProcRoadmapProcStationList"  filter=".nodrag" is='draggable' animation="300" force-fallback="true" group="inner" item-key="index" :allbackOnBody="true" @add="addInner" :disabled="disabled" @start="handleInnerStart">
                      <template v-slot:item="item">
                        <div class="site-box" v-if="element.open">
                          <div class="relative">
                            <span class="line-icon">
                              <environment-two-tone two-tone-color="#3E8FF7" />
                            </span>
                            <span class="pl-15">
                              {{getFieldText(lineList,item.element.stationId,'id','lineNo')}}-{{getFieldText(lineList,item.element.stationId,'id','stationNo')}}
<!--                              {{item.element.lineNo}}-{{item.element.stationNo}}-->
                            </span>
                          </div>
                          <div>
                            <a-checkbox class="nodrag" v-model:checked="item.element.mainStationBoolean" :disabled="disabled">{{$t('hangManage.mainStation')}}</a-checkbox>
<!--                            <a-checkbox v-model:checked="item.element.mainAuxiliaryStation" :checked=" false ">主站 </a-checkbox>-->
                          </div>
                          <div>{{item.element.proportion}}</div>
                          <div>
                            {{item.element.type == 1 ? $t('other.save'):$t('other.normal')}}

                            <span v-if="showMsg(item.element, 'all')"> ，（ </span>
                            <span v-if="showMsg(item.element, 'color')">{{$t('basicData.color') }}：{{item.element.colorList.join(',')}}；</span>
                            <span v-if="showMsg(item.element, 'size')">{{ $t('basicData.size') }}： {{item.element.sizeList.join(',')}}；</span>
                            <span v-if="showMsg(item.element, 'po')">PO： {{item.element.poList.join(',')}}；</span>
                            <span v-if="showMsg(item.element, 'cutterNo')">{{$t('hangManage.bedNo')}}： {{item.element.cutterNoList.join(',')}}；</span>
                            <span v-if="showMsg(item.element, 'tailorBill')">{{$t('hangManage.cut')}}： {{item.element.tailorBillList.join(',')}}</span>
                            <span v-if="showMsg(item.element, 'all')"> ）</span>
                          </div>

                          <div>
                            <span v-if="item.element.staffId"> {{getFieldText(staffList,item.element.staffId,'id','staffNo')}}-{{getFieldText(staffList,item.element.staffId,'id','nickName')}}
                              {{getFieldText(staffList,item.element.staffId,'id','skillGrade')}}
                              {{arrToStr(staffList,item.element.staffId,'id','professionNameList')}}
                            </span>
                          </div>

                          <div v-if="!disabled"  class="nodrag">
                            <a-button type="link" class="primary-link" @click="editSite(index, item.index, item.element)">{{ $t('common.editor') }}</a-button>
                            <span class="close-icon" @click="handelCancel(item.index, true, index)">
                              <close-outlined />
                            </span>
                          </div>
                        </div>
                      </template>
                    </draggable>
                  </div>

                </template>
              </draggable>
            </a-col>
            <a-col :span="8 " class="choose-container">
              <chooseList ref="chooseListRef" :processId="processId" :scheduleInfo="scheduleInfo" :tableList="tableList"  @onOutGroupEnd="onOutGroupEnd" @onChooseProcess="onChooseProcess" @onInnerGroupEnd="onInnerGroupEnd" :urlType="urlType" />
            </a-col>
          </a-row>
          <editStation ref="editStationRef" @ok="onStationOK" />
        </div>
      </div>
      <div class="operate-page-btns">
        <a-space v-if="disabled">
          <a-button class="cancel" @click="returnBack">{{ $t('other.back') }}</a-button>
        </a-space>
        <a-space v-else>
          <a-button class="cancel" @click="previousStep">{{ $t('other.lastStep') }}</a-button>
          <a-button type="primary" class="confirm" @click="handleOk" >{{$t('common.ok')}}</a-button>
        </a-space>
      </div>
    </a-spin>
  </div>
</template>

<script setup>
import draggable from 'vuedraggable'
import { ref,computed, onMounted, nextTick } from 'vue'
import {  routeHeader, viewRouteHeader } from './newModules/routeChartConfig'
import { PlusSquareOutlined, MinusSquareOutlined, CloseOutlined, EnvironmentTwoTone } from '@ant-design/icons-vue'
import chooseList from './newModules/chooseList.vue'
import editStation from './newModules/editStation.vue'
import { cloneDeep, uniqBy ,pick } from 'lodash'
import { message } from 'ant-design-vue'
import axios from '@/utils/request'
import {  getFieldText } from '@/utils'
import {  useRouter } from 'vue-router'
import { store } from '@/store'
import i18n from '@/locales/index'
const { t } = i18n.global

let router = useRouter()

// import axios from "@/utils/request"
import { useRoute } from 'vue-router'
let disabled = ref(false)
const formState = ref({})
let formRef = ref()
let processOption = ref([])
let loading = ref(false)
let editStationRef = ref()
let route = useRoute()
let tableList = ref([])
let routeInfo = ref({})
let chooseListRef = ref({})
let originList = ref(tableList.value)
let sortFlag = ref(false)
let sortInnerFlag = ref(false)
let processId = ref(null) // 工序版本id
let editProcIndex = ref(0)
let editStationIndex = ref(0)
let isAdd = ref(false)
let isEdit = ref(false)
let originSortList = ref([])
let maxNum = ref(0)
let editProcessList = ref({})
let scheduleInfo = ref({})
let ieCreateRoadMapData = ref({})
let lineList = ref([])
let staffList = ref([])
let moInfo = ref({})
let tempObj = ref({})
let urlType = ref("")
const tabs = computed(() => {
  return store.state.setting.tabs
})
const arrToStr = (ary, value, itemName, field) => {
  const info = ary.filter(i => i[itemName] == value)
  let arr =  info.length ? info[0][field] : []
  return arr ? `(${ arr.join(",")})` : ''
}

const previousStep = async (isSuccess) => {
  const tabList = cloneDeep(tabs.value)
  let changeTabs = tabList.filter((i) => {
    if (isSuccess) {
      return !['/makeManage/scheduleRoute/edit', route.path].includes(i.path)
    } else {
      return i.path !== route.path
    }
  })
  await store.commit('updateState', { tabs: changeTabs })
  router.push({
    path: '/makeManage/scheduleProcess/edit',
    query: { id: editProcessList.value.id }
  })
}
const returnBack = async (isSuccess) => {
  const tabList = cloneDeep(tabs.value)
  let changeTabs = tabList.filter((i) => {
    if (isSuccess) {
      return !['/makeManage/scheduleRoute/details', route.path].includes(i.path)
    } else {
      return i.path !== route.path
    }
  })
  await store.commit('updateState', { tabs: changeTabs })
  if (route.query.type == 'sch'){
    router.push({
      path: '/makeManage/autoScheduleLocal'
    })
  }else if (route.query.type == 'loc'){
    router.push({
      path: '/makeManage/autoSchLocal'
    })
  }else if(route.query.type == 'ie'){
    router.push({
      path: '/makeManage/autoScheduleOnline'
    })
  }else{
    router.back
  }
}

const returnBacks = async (isSuccess) => {
  const tabList = cloneDeep(tabs.value)
  let changeTabs = tabList.filter((i) => {
    if (isSuccess) {
      return !['/makeManage/scheduleRoute/edit', route.path].includes(i.path)
    } else {
      return i.path !== route.path
    }
  })
  await store.commit('updateState', { tabs: changeTabs })
  router.push({
    path: '/makeManage/autoScheduleOnline'
  })

}
const handleOk = async () => {
  loading.value = true
  try {
    const res = await axios.postAction('/api/mo/ie-roadmap/commit',doParams())
    if (res.success){
      loading.value = false
      await returnBacks(true)
    }
  }catch (err){
    loading.value = false
    console.log(err)
  }
}
const doParams = () => {
  let params = {}
  let mapObj = pick(ieCreateRoadMapData.value, ['id', 'moId', 'ieRoadmapId', 'processId', 'name' ,'hangerLineIdList', 'targetYieldDay','firstProcess', 'lastProcess', 'remark'])

  if (tableList.value){
    tableList.value.forEach(item=>{
      item.forwardIntegration = item.forwardMerge ? 1 : 0
      item.enable = item.effect ? 1 : 0
      if (item.moProcRoadmapProcStationList){
        item.moProcRoadmapProcStationList.forEach(
            (el,i)=> {
              el.sort = i + 1
              el.mainAuxiliaryStation = el.mainAuxiliaryStation?el.mainAuxiliaryStation:2
            }
        )
      }
    })
  }
  mapObj.moProcRoadmapProcList = tableList.value
  mapObj.firstProcess = formState.value.firstProcess
  mapObj.lastProcess = formState.value.lastProcess
  params.ieRoadmapProcRoadmapVO = mapObj
  if (editProcessList.value){
    editProcessList.value.status = 2;
  }
  params.ieRoadmapVO =editProcessList.value
  params.moId = mapObj.moId
  params.ieRoadmapId = mapObj.ieRoadmapId
  // console.log(params,'params++++++++++++++++++++++++++++++++++++')
  return params
}

const handleStart = () => {
  sortFlag.value = true
  originList.value = cloneDeep(tableList.value)
}
const changeProcessInfo = (isDelete) => {
  // processOption.value = tableList.value
  if (isDelete) {
    formState.value.firstProcess = undefined
    formState.value.lastProcess = undefined
  }
}
const add = async (e) => {
  sortFlag.value = false
  await nextTick()
  if (e.newIndex === 0) {
    message.warning(t('other.firstStationMCanHang') )
    tableList.value.splice(0, 1)
    initSortInfo()
  }
  changeProcessInfo()
}
const handleSort = (e) => {
  if (sortFlag.value) {
    if (e.newIndex == 0) {
      message.warning(t('other.firstStationMCanHangProcess'))
      tableList.value = originList.value
    } else {
      initSortInfo()
      tableList.value.forEach((i, index) => { i.sort = originSortList.value[index] })
    }
  }
}
const handelCancel = (key, isInner, outKey) => {
  if (isInner) {
    tableList.value[outKey].moProcRoadmapProcStationList.splice(key, 1)
  } else {
    tableList.value.splice(key, 1)
    initSortInfo()
    changeProcessInfo(true)
  }
}
const onOutGroupEnd = () => {
  tableList.value = tableList.value.map(i => {
    let obj = { ...i }
    if (obj.open == undefined) obj.open = true
    obj.moProcRoadmapProcStationList = obj.moProcRoadmapProcStationList || []
    if (!obj.sort) {
      let newSortNo = ++maxNum.value
      obj.sort = newSortNo
    }
    return obj
  })
  initSortInfo()

  tableList.value.forEach((i, index) => { i.sort = originSortList.value[index] })
}
const handleInnerStart = () => {
  sortInnerFlag.value = true
  originList.value = cloneDeep(tableList.value)
}
const onSortInner = () => {
  let lists = cloneDeep(tableList.value)
  let flag1 = lists[0].moProcRoadmapProcStationList.some(i => i.role != '2')
  lists.splice(0, 1)
  let flag2 = lists.reduce((prev, next) => {
    return prev.concat(...(next.moProcRoadmapProcStationList ? next.moProcRoadmapProcStationList : []))
  }, []).some(i => i.role == 2)
  if (flag1) message.warning(t('other.firstProcessCanHang'))
  if (flag2) message.warning(t('other.hangStationMustDownFirstProcessCanHang'))
  let mergeFlag = lists.some(i => i.forwardMerge && i.moProcRoadmapProcStationList.length > 0)
  if (mergeFlag) message.warning(t('other.forwardMergeProcess'))
  let isUniq = lists.every(i => isUniqInner(i.moProcRoadmapProcStationList).isUniq)
  if (flag1 || flag2 || mergeFlag || !isUniq) tableList.value = originList.value
}
const isUniqInner = (list) => {
  let uniqList = uniqBy(list, 'stationId')
  let isUniq = uniqList.length == list.length
  if (!isUniq) message.warning(t('other.sameProcessCanNotSameStation'))
  return {
    isUniq,
    uniqList
  }
}
const onAddInner = () => {
  tableList.value.forEach((el, index) => {
    if (index == 0) {
      if (el.moProcRoadmapProcStationList && el.moProcRoadmapProcStationList.some(i => i.role != '2')) {
        message.warning(t('other.firstProcessCanHang'))
        el.moProcRoadmapProcStationList = el.moProcRoadmapProcStationList.filter(i => i.role == '2')
      }
      let isUniqInfo = isUniqInner(el.moProcRoadmapProcStationList)
      if (!isUniqInfo.isUniq) el.moProcRoadmapProcStationList = isUniqInfo.uniqList
    } else {
      if (el.forwardMerge) {
        if (el.moProcRoadmapProcStationList.length > 0) {
          message.warning(t('other.forwardMergeProcess'))
          el.moProcRoadmapProcStationList = []
        }
      } else {
        if (el.moProcRoadmapProcStationList && el.moProcRoadmapProcStationList.some(i => i.role == '2')) {
          message.warning(t('other.hangStationMustDownFirstProcessCanHang'))
          el.moProcRoadmapProcStationList = el.moProcRoadmapProcStationList.filter(i => i.role != '2')
        }

        let isUniqInfo = isUniqInner(el.moProcRoadmapProcStationList)
        if (!isUniqInfo.isUniq) el.moProcRoadmapProcStationList = isUniqInfo.uniqList
      }

    }
  })
}
const addInner = async () => {
  await nextTick()
  if (sortInnerFlag.value) {
    onSortInner()
  } else {
    onAddInner()
  }
  sortInnerFlag.value = false
}
const onInnerGroupEnd = () => {
  tableList.value.map(el => {
    el.moProcRoadmapProcStationList = el.moProcRoadmapProcStationList.map(i => ({ ...i }))
    return el
  })
}
const toggleAll = (open) => {
  tableList.value.forEach(i => {
    i.open = open
  })
}
const clearList = () => {
  let lists = cloneDeep(tableList.value).splice(0, 1)
  lists[0].moProcRoadmapProcStationList = []
  tableList.value = lists
  initSortInfo()
  changeProcessInfo(true)

}
const onCheckChange = (element) => {
  if (element.forwardMerge) element.moProcRoadmapProcStationList = []
}
const editSite = (parentIndex, index, record) => {
  // console.log(parentIndex, index, record,'+++++++++++++++++++++')
  let lineNo1 = getFieldText(lineList.value,record.stationId,'id','lineNo')
  let stationNo1 = getFieldText(lineList.value,record.stationId,'id','stationNo')
  let name = lineNo1 +'-'+ stationNo1
  // role 角色 1桥接站 2挂片站 3车缝站 4存储站 5质检站 6空衣架回收站
      // `${record.lineNo}-${record.stationNo}`
  editProcIndex.value = parentIndex
  editStationIndex.value = index
  editStationRef.value.edit(name, record, moInfo.value,staffList.value)
}
const onStationOK = (value) => {
  let datas = cloneDeep(tableList.value)
  datas.forEach((item, index) => {
    if (index == editProcIndex.value) {
      item.moProcRoadmapProcStationList && item.moProcRoadmapProcStationList.map((el, i) => {
        if (i == editStationIndex.value) {
          Object.assign(el, value)
        }
        return el
      })
    }
  })
  tableList.value = datas
  // console.log(tableList.value)
}
// const initFormInfo = async (info) => {
//   let formValue = route.path == '/makeManage/routeChart/add' ? {} : pick(info, ['name', 'firstProcess', 'lastProcess'])
//   await nextTick()
//   formState.value = formValue
// }
const initSortInfo = () => {
  originSortList.value = tableList.value.map(i => i.sort).filter(i => i != undefined).sort((a, b) => a - b)
  maxNum.value = Math.max(...originSortList.value)
}
const initTableList = (list, isNew) => {
  // console.log(list,'list-*-*-*-***************************+666+++++++++++++++++++++++++')
  list.forEach(i => {
    i.open = true
    i.forwardMerge = i.forwardIntegration == 1
    i.enable = isNew ? 1 : i.enable
    i.effect = i.enable == 1
    if (i.moProcRoadmapProcStationList) {
      i.moProcRoadmapProcStationList.forEach(i => {
        i.mainStationBoolean = i.mainAuxiliaryStation == 1
      })
    } else {
      i.moProcRoadmapProcStationList = []
    }
  })
  tableList.value = list
  initSortInfo()
}
const initRouteListInfo = (info) => {
  routeInfo.value = info
  processId.value = isAdd.value ? null : info.processId
  initTableList(info.moProcRoadmapProcList || [])
  changeProcessInfo()
}
const showMsg = (record, type) => {
  if (type == 'all') {
    return ['colorList', 'sizeList', 'poList', 'cutterNoList', 'tailorBillList'].some(i => record[i] && record[i].length)
  } else {
    return record[`${type}List`] && record[`${type}List`].length
  }
}
const onChooseProcess = (list, processVersionId) => {
  list.forEach((i, index) => {
    i.sort = index + 1
  })
  initTableList(list, true)
  // processOption.value = tableList.value
  processId.value = processVersionId
}
const initMethod = async () => {
  if (route.query.id){
    let resSch = await axios.getAction('/api/mo/ie-roadmap/get',{id:route.query.id})
    if (resSch.success){
      scheduleInfo.value = resSch.data;
      // processOption.value = (resSch.data.ieRoadmapProcVO && resSch.data.ieRoadmapProcVO.detailList && resSch.data.ieRoadmapProcVO.detailList )|| []
      if (scheduleInfo.value.ieRoadmapProcVO){
        formState.value.name = t('common.systemAutoGenerate')
      }
      if(resSch.data.moId){
        let resMo = await axios.getAction('/api/mo/mo/get',{id:resSch.data.moId})
        if (resMo.success){
          moInfo.value = resMo.data;
        }
      }
    }
  }
  //生成路线图返回参数更改为 统一接口返回参数  ieRoadmapVO  ieRoadmapProcRoadmapVO
  tempObj.value = JSON.parse(localStorage.getItem("ieCreateRoadMapData"))
  editProcessList.value = tempObj.value.ieRoadmapVO
  ieCreateRoadMapData.value = tempObj.value.ieRoadmapProcRoadmapVO
  processOption.value = (ieCreateRoadMapData.value && ieCreateRoadMapData.value.moProcRoadmapProcList )|| []
  if (ieCreateRoadMapData.value.hangerLineIdList){
    let resLine = await axios.postAction('/api/device/station/get-hangerLineId-by-station',{hangerLineIdList:ieCreateRoadMapData.value.hangerLineIdList})
    if (resLine.success){  lineList.value = resLine.data; }
  }
  if (ieCreateRoadMapData.value) {
    formState.value.firstProcess = ieCreateRoadMapData.value.firstProcess ?? ''
    formState.value.lastProcess = ieCreateRoadMapData.value.lastProcess ?? ''
  }
  //遍历站点设置为 普通站 type=0
  ieCreateRoadMapData.value && ieCreateRoadMapData.value.moProcRoadmapProcList.forEach(item=>{
    if (item.moProcRoadmapProcStationList){
      item.moProcRoadmapProcStationList.forEach(i=>{
        if (!i.type){
          i.type = "0"
        }
      })
    }
  })
  initRouteListInfo(ieCreateRoadMapData.value)
  tableList.value = ieCreateRoadMapData.value.moProcRoadmapProcList
  initTableList( tableList.value)
  // console.log(ieCreateRoadMapData.value,'ieCreateRoadMapData************************************生成路线图信息*****')
  // console.log(tableList.value,'tableList************************************返回工序*****')
  // console.log(editProcessList.value,'editProcessList************************************生成路线图之前的编辑工序*****')
  const resStaff = await axios.postAction('/api/basic/staff/list')
  if (resStaff.success) staffList.value = resStaff.data
}
const initMethodDetailsLocYun = async () => {
  if (route.query.id){
    let res = await axios.getAction('/api/mo/auto-roadmap-proc-roadmap/get',{id:route.query.id})
    // console.log('yun+++++++++++++++',res)
    if (res.success){
      if (res.data.autoRoadmapId){
        let resSch = await axios.getAction('/api/mo/ie-roadmap/get',{id:res.data.autoRoadmapId})
        if (resSch.success){
          scheduleInfo.value = resSch.data;
          // processOption.value = (resSch.data.ieRoadmapProcVO && resSch.data.ieRoadmapProcVO.detailList && resSch.data.ieRoadmapProcVO.detailList )|| []
          if (scheduleInfo.value.ieRoadmapProcVO){
            formState.value.name = scheduleInfo.value.ieRoadmapProcVO.name
          }
          // console.log(scheduleInfo.value,'scheduleInfo**************************排产单及工序信息')
          if(resSch.data.moId){
            let resMo = await axios.getAction('/api/mo/mo/get',{id:resSch.data.moId})
            if (resMo.success){
              moInfo.value = resMo.data;
            }
          }

        }
      }

      ieCreateRoadMapData.value = res.data   // 生成{{$t('hangManage.road')}}返回数据
      processOption.value = (ieCreateRoadMapData.value && ieCreateRoadMapData.value.moProcRoadmapProcList )|| []

      if (ieCreateRoadMapData.value.hangerLineIdList){
        let resLine = await axios.postAction('/api/device/station/get-hangerLineId-by-station',{hangerLineIdList:ieCreateRoadMapData.value.hangerLineIdList})
        if (resLine.success){  lineList.value = resLine.data; }
      }
      if (ieCreateRoadMapData.value) {
        formState.value.firstProcess = ieCreateRoadMapData.value.firstProcess ?? ''
        formState.value.lastProcess = ieCreateRoadMapData.value.lastProcess ?? ''
      }

      initRouteListInfo(ieCreateRoadMapData.value)
      tableList.value = ieCreateRoadMapData.value.moProcRoadmapProcList
      initTableList( tableList.value)
      // console.log(ieCreateRoadMapData.value,'ieCreateRoadMapData************************************生成路线图信息*****')
      // console.log(tableList.value,'tableList************************************返回工序*****')
      // console.log(editProcessList.value,'editProcessList************************************生成路线图之前的编辑工序*****')
      const resStaff = await axios.postAction('/api/basic/staff/list')
      if (resStaff.success) staffList.value = resStaff.data


      scheduleInfo.value = res.data;
      if (scheduleInfo.value.ieRoadmapProcVO){
        formState.value.name = scheduleInfo.value.ieRoadmapProcVO.name
      }
      // console.log(scheduleInfo.value,'scheduleInfo**************************排产单及工序信息')
      if(res.data.moId){
        let resMo = await axios.getAction('/api/mo/mo/get',{id:res.data.moId})
        if (resMo.success){
          moInfo.value = resMo.data;
        }
      }

    }
  }

}

const initMethodDetailsLoc = async () => {
  if (route.query.id){
    let res = await axios.getAction('/api/mo/auto-roadmap-proc-roadmap/get',{id:route.query.id})
    // console.log('res loc +++++++++++++++++++++',res)
    if (res.success){
      if (res.data.autoRoadmapId){
        let resSch = await axios.getAction('/api/mo/auto-roadmap/get',{id:res.data.autoRoadmapId})
        if (resSch.success){
          scheduleInfo.value = resSch.data;
          // processOption.value = (resSch.data.ieRoadmapProcVO && resSch.data.ieRoadmapProcVO.detailList && resSch.data.ieRoadmapProcVO.detailList )|| []
          if (scheduleInfo.value.autoRoadmapProcVO){
            formState.value.name = scheduleInfo.value.autoRoadmapProcVO.name
          }
          if(resSch.data.moId){
            let resMo = await axios.getAction('/api/mo/mo/get',{id:resSch.data.moId})
            if (resMo.success){
              moInfo.value = resMo.data;
            }
          }

        }
      }



      ieCreateRoadMapData.value = res.data   // 生成路线图返回数据


      processOption.value = (ieCreateRoadMapData.value && ieCreateRoadMapData.value.moProcRoadmapProcList )|| []

      if (ieCreateRoadMapData.value.hangerLineIdList){
        let resLine = await axios.postAction('/api/device/station/get-hangerLineId-by-station',{hangerLineIdList:ieCreateRoadMapData.value.hangerLineIdList})
        if (resLine.success){  lineList.value = resLine.data; }
        console.log(lineList.value,'lineList.value------------------')
      }
      if (ieCreateRoadMapData.value) {
        formState.value.firstProcess = ieCreateRoadMapData.value.firstProcess ?? ''
        formState.value.lastProcess = ieCreateRoadMapData.value.lastProcess ?? ''
      }

      initRouteListInfo(ieCreateRoadMapData.value)
      tableList.value = ieCreateRoadMapData.value.moProcRoadmapProcList
      initTableList( tableList.value)
      // console.log(ieCreateRoadMapData.value,'ieCreateRoadMapData************************************生成路线图信息*****')
      // console.log(tableList.value,'tableList************************************返回工序*****')
      // console.log(editProcessList.value,'editProcessList************************************生成路线图之前的编辑工序*****')

      const resStaff = await axios.postAction('/api/basic/staff/list')
      if (resStaff.success) staffList.value = resStaff.data


      scheduleInfo.value = res.data;
      if (scheduleInfo.value.ieRoadmapProcVO){
        formState.value.name = scheduleInfo.value.ieRoadmapProcVO.name
      }
      // console.log(scheduleInfo.value,'scheduleInfo**************************排产单及工序信息')
      if(res.data.moId){
        let resMo = await axios.getAction('/api/mo/mo/get',{id:res.data.moId})
        if (resMo.success){
          moInfo.value = resMo.data;
        }
      }

    }
  }

}

const initMethodIe = async () => {
  if (route.query.id){
    let res = await axios.getAction('/api/mo/ie-roadmap-proc-roadmap/get',{id:route.query.id}) //路线图信息
    // console.log('res ie +++++++++++++++++++++',res)
    if (res.success){
      if (res.data.ieRoadmapId){
        let resSch = await axios.getAction('/api/mo/ie-roadmap/get',{id:res.data.ieRoadmapId})
        // console.log('resSch ie +++++++++++++++++++++',resSch)
        if (resSch.success){
          scheduleInfo.value = resSch.data;
          if (scheduleInfo.value.ieRoadmapProcVO){
            formState.value.name = scheduleInfo.value.ieRoadmapProcVO.name || ''
          }
          // console.log(scheduleInfo.value,'scheduleInfo**************************排产单及工序信息')
          if(resSch.data.moId){
            let resMo = await axios.getAction('/api/mo/mo/get',{id:resSch.data.moId})
            if (resMo.success){
              moInfo.value = resMo.data;
            }
          }

        }
      }
      ieCreateRoadMapData.value = res.data   // 生成路线图返回数据
      processOption.value = (ieCreateRoadMapData.value && ieCreateRoadMapData.value.moProcRoadmapProcList )|| []
      if (ieCreateRoadMapData.value.hangerLineIdList){
        let resLine = await axios.postAction('/api/device/station/get-hangerLineId-by-station',{hangerLineIdList:ieCreateRoadMapData.value.hangerLineIdList})
        if (resLine.success){  lineList.value = resLine.data; }
      }
      if (ieCreateRoadMapData.value) {
        formState.value.firstProcess = ieCreateRoadMapData.value.firstProcess ?? ''
        formState.value.lastProcess = ieCreateRoadMapData.value.lastProcess ?? ''
      }
      initRouteListInfo(ieCreateRoadMapData.value)
      tableList.value = ieCreateRoadMapData.value.moProcRoadmapProcList
      initTableList( tableList.value)
      // console.log(ieCreateRoadMapData.value,'ieCreateRoadMapData************************************生成路线图信息*****')
      // console.log(tableList.value,'tableList************************************返回工序*****')
      // console.log(editProcessList.value,'editProcessList************************************生成路线图之前的编辑工序*****')

      const resStaff = await axios.postAction('/api/basic/staff/list')
      if (resStaff.success) staffList.value = resStaff.data

      scheduleInfo.value = res.data;
      if (scheduleInfo.value.ieRoadmapProcVO){
        formState.value.name = scheduleInfo.value.ieRoadmapProcVO.name
      }
      // console.log(scheduleInfo.value,'scheduleInfo**************************排产单及工序信息')
      if(res.data.moId){
        let resMo = await axios.getAction('/api/mo/mo/get',{id:res.data.moId})
        if (resMo.success){
          moInfo.value = resMo.data;
        }
      }
    }
  }
}

defineExpose({
  formRef,
  // formState,
  processId,
  tableList
})

onMounted(async () => {
  tableList.value = []
  originSortList.value = []
  isAdd.value = route.path == '/makeManage/scheduleRoute/add'
  isEdit.value = route.path == '/makeManage/scheduleRoute/edit'
  disabled.value = route.path == '/makeManage/scheduleRoute/edit'? false:true
  urlType.value = route.query.type
  if (urlType.value == 'loc'){
    //工厂本地
    await initMethodDetailsLoc()
  }else if (urlType.value == 'sch'){
    //工厂云
    await initMethodDetailsLocYun()
  }else if (urlType.value == 'ie'){
    //ie
    await initMethodIe()
  }else{
    //添加路线图
    await initMethod()
  }
  //
  // if (disabled.value){
  //   await initMethodDetails()
  // }else{
  //   await initMethod()
  // }
  // 新增
  // initFormInfo()

})
</script>